package com.imflea.zero.api;

import com.alibaba.fastjson.JSONObject;
import com.imflea.zero.constants.ZeroContant;
import com.imflea.zero.util.base.JsonResult;
import com.imflea.zero.util.base.CommonUtils;
import com.imflea.zero.poc.JsonFileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.List;

/**
 * @author 祥保玉
 * @PackageName: com.imflea.zero.util
 * @ClassName: DoMain
 * @Description
 * @date 2022-04-12  09:47:52
 */
@RestController
@RequestMapping("/api/poc")
@Api(value = "IOT设备API-基础公共api", tags = "基础公共api")
@Slf4j
public class PocAPI {
    //    public static final String baseModulePath = "E:\\项目\\畜牧项目\\二期\\poc验证\\mini\\";
    public final String baseTargetPath = "/home/farmplus/poc/project/";

    public final String baseSourceBasePath = "/home/farmplus/poc/mini/";

    @PostMapping("/generator")
    @ApiOperation(value = "尝试")
    @ApiOperationSupport(order = 1)
    public JsonResult<Boolean> generator() throws IOException {
        //路径
        String compileConfig = "compile.json";
        String file = baseSourceBasePath + compileConfig;

        BufferedReader reader = null;
        String laststr = "";
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
            reader = new BufferedReader(inputStreamReader);
            String tempString = null;
            while ((tempString = reader.readLine()) != null) {
                //数据获取
                laststr += tempString;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //json 解析
        JSONObject jasonData = JSONObject.parseObject(laststr);
        String version = jasonData.getString("version");
        String productName = jasonData.getString("productName");
        String targetProjectPath = baseTargetPath + productName;
        //1、 创建项目根目录
        if (!new File(targetProjectPath).exists()) {
            new File(targetProjectPath).mkdir();
        }


        String productCategory = jasonData.getString("productCategory");
        // 2、这是copy目录及子目录中所有文件到目标目录
        List<String> listProductCategory = JSONObject.parseArray(productCategory, String.class);

        for (String str : listProductCategory) {
            System.out.println(str);
            if (new File(baseSourceBasePath + File.separator + str).exists()) {
                FileUtils.copyDirectory(new File(baseSourceBasePath + File.separator + str), new File(targetProjectPath + File.separator + str));
            }
        }


        // 3、copy文件为指定的文件名
        String productFiles = jasonData.getString("productFile");
        List<JSONObject> fileNames = JSONObject.parseArray(productFiles, JSONObject.class);
        for (JSONObject fileName : fileNames) {
            String source = fileName.getString("source");
            String target = fileName.getString("target");
            File targetFile = new File(targetProjectPath + File.separator + target);
            File sourceFile = new File(baseSourceBasePath + File.separator + source);
            if (targetFile.exists()) {
                targetFile.delete();
            }
            FileUtils.copyFile(sourceFile, targetFile);
        }

        //4、替换文件中的变量
        String replaceFile = jasonData.getString("replaceFile");
        List<JSONObject> replaceFiles = JSONObject.parseArray(replaceFile, JSONObject.class);
        for (JSONObject job : replaceFiles) {
            String fileName = job.getString("fileName");
            String jsonStr = JsonFileUtils.readJsonFile(targetProjectPath + File.separator + fileName);
            System.out.println(jsonStr);
            List<JSONObject> vars = JSONObject.parseArray(job.getString("list"), JSONObject.class);
            for (JSONObject var : vars) {
                String key = var.getString("key");
                String value = var.getString("value");
                jsonStr = jsonStr.replace(key, value);
                JsonFileUtils.writeJsonFile(jsonStr, targetProjectPath + File.separator + fileName);
            }
        }
        System.out.println(this.proccessCmd("", ""));
        return new JsonResult<>(ZeroContant.getSuccessCode(), true);
    }


    //npm run build:custom wechat-dev
    public String proccessCmd(String cmd, String pwd) {

        if (CommonUtils.isNull(cmd)) {
            cmd = "npm run build:custom wechat-dev";
        }
        if (CommonUtils.isNull(pwd)) {
            pwd = "/home/farmplus/poc/project/weixin-dev";
        }

        Runtime run = Runtime.getRuntime();
        File wd = new File("/bin");
        System.out.println(wd);
        Process proc = null;
        try {
            log.error("/bin/bash");
            proc = run.exec("/bin/bash", null, wd);
        } catch (IOException e) {
            e.printStackTrace();

        }
        if (proc != null) {
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
            out.println("cd " + pwd);
            out.println(cmd);
            try {
                String line;
                while ((line = in.readLine()) != null) {
                    System.out.println(line);
                }
                proc.waitFor();
                in.close();
                out.close();
                proc.destroy();

            } catch (Exception e) {
                e.printStackTrace();
            }
            out.println("exit");
        } else {
            System.out.println("proc is null");
        }
        return "success";
    }

    @PostMapping("/build")
    @ApiOperation(value = "编译")
    @ApiOperationSupport(order = 2)
    public JsonResult<Boolean> build(String cmd) throws IOException {
        System.out.println(this.proccessCmd(cmd, ""));
        return new JsonResult<>(ZeroContant.getSuccessCode(), true);
    }
}

